<?php
class tbdata_api_amazon extends tbdata_api_request{

    var $app_key = 'AKIAI7AMQXRBU456IIJQ';
    var $app_secret = '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';
    var $api_url = 'http://webservices.amazon.cn/onca/xml?';
	public function __contruct(){

	}
    public function get_items(){
		/*
		$params['Operation'] = 'BrowseNodeLookup';
		$params['BrowseNodeId'] = '665002051';
		*/

		$params['Operation'] = 'ItemSearch';
		$params['Keywords'] = 'iphone4 8G';
		$params['SearchIndex'] = 'Electronics';
		$params['ResponseGroup'] = 'ItemAttributes,Offers,Images,Reviews';

		$this->api_url = $this->get_request_url($this->app_secret,$params);
		return $this->request(array());
    }

	public function request($params){
        $http = kernel::single('base_httpclient');
        $xml = kernel::single('base_xml');
        $net_result = $http->get($this->api_url,$params);
		echo $net_result;exit;
        return $xml->xml2array($net_result);
		
	}

	function get_request_url($secret_key, $params, $access_key = false, $version = '2011-08-01') {
		
		$params = $params+$this->system_static_params();

		$uri_elements = parse_url($params['base_url']);

		$request = $uri_elements['query'];

		unset($params['base_url']);
		$parameters = $params;

		$parameters['Timestamp'] = time();
		$parameters['Version'] = $version;
		if (strlen($access_key) > 0) {
			$parameters['AWSAccessKeyId'] = $access_key;
		}   
	 
		ksort($parameters);
	 
		foreach ($parameters as $parameter => $value) {
			$parameter = str_replace("%7E", "~", rawurlencode($parameter));
			$value = str_replace("%7E", "~", rawurlencode($value));
			$request_array[] = $parameter . '=' . $value;
		}   
	 
		$new_request = implode('&', $request_array);
	 
		$signature_string = "GET\n{$uri_elements['host']}\n{$uri_elements['path']}\n{$new_request}";
	 
		$signature = urlencode(base64_encode(hash_hmac('sha256', $signature_string, $secret_key, true)));

		return "http://{$uri_elements['host']}{$uri_elements['path']}?{$new_request}&Signature={$signature}";
	}

    public function system_static_params(){
        return array('base_url'=>$this->api_url,'Timestamp'=>date('Y-m-d H:i:s'),'Service'=>'AWSECommerceService','AWSAccessKeyId'=>$this->app_key,'AssociateTag'=>'zrlister-23',);
    }

}